package com.ysd.lis.util;

import cn.hutool.core.io.FileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/***
 *@title EasyExcelExport
 *@author WH
 *@version 1.0.0
 *@create 2025/5/8 17:03
 **/
@Slf4j
public class EasyExcelExport {
    /**
     * 导出为多sheet页excel数据，不支持大数据量导出，可为多数据表结果集
     *
     * @param fileName 文件名称 如：personal用户管理xlsx
     * @param response 响应体
     * @param sheets   封装后的多sheet页model
     */
    public static void downloadMultipleSheetExcel(String fileName, HttpServletResponse response, List<EasyExcelSheet> sheets) {
        ExcelWriter excelWriter=null;
        try {
            response.setCharacterEncoding("utf-8");
            String excelType = FileUtil.extName(fileName);
            String sheetName = FileUtil.mainName(fileName);

            // 这里URLEncoder.encode可以防止中文乱码
            String encodeFileName = URLEncoder.encode(sheetName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encodeFileName + "." + "xlsx");

            ExcelTypeEnum excelTypeEnum = ExcelTypeEnum.XLSX;
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            if ("xls".equals(excelType)) {
                excelTypeEnum = ExcelTypeEnum.XLS;
                response.setContentType("application/vnd.ms-excel");
            } else if ("csv".equals(excelType)) {
                excelTypeEnum = ExcelTypeEnum.CSV;
                response.setContentType("text/csv");
            }

            excelWriter = EasyExcel.write(response.getOutputStream()).excelType(excelTypeEnum).build();
            ExcelWriter finalExcelWriter = excelWriter;
            for (EasyExcelSheet sheet : sheets) {
                // sheet页位置，sheet页名称
                WriteSheet writeSheet = EasyExcel.writerSheet(sheet.getSheetIndex(), sheet.getSheetName())
                        // 表头实体
                        .head(sheet.getHeadClass())
                        // 导出内容格式，默认最大列为基准，具体样式可自定义实现（这里可以百度一下）
                        .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                        .build();
                finalExcelWriter.write(sheet.getDataset(), writeSheet);
            }
        } catch (Exception e) {
            // 重置响应，避免部分内容写入
            if (!response.isCommitted()) {
                response.reset();
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
            log.error("文件【{}】下载失败");
            log.error(e.getMessage(), e);
        }finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }
}
